package com.cloud.rou.im.client.statemachine;

import com.cloud.rou.im.client.msg.ChatMessageQueueExecutor;
import com.cloud.rou.im.client.msg.CheckAckProcessor;
import com.cloud.rou.im.client.msg.ExecutorAggregation;
import com.cloud.rou.im.msg.Msg;

import java.io.IOException;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-11-22 23:14
 */
public class StateMachineFactory {

    public static StateMachine getStateMachine(){

        ExecutorAggregation aggregation = new ExecutorAggregation();

        StateMachine.Builder builder = StateMachine.builder();
        builder.initialState(MsgState.WAIT_SEND);
        builder
                .state(MsgState.WAIT_SEND)
                .event(MsgEvent.SEND)
                .toStateAndAction(MsgState.WAIT_REPLY, aggregation::send);
        builder
                .state(MsgState.WAIT_REPLY)
                .event(MsgEvent.ACK)
                .toStateAndAction(MsgState.END,aggregation::removeAck);
        builder
                .state(MsgState.WAIT_REPLY)
                .event(MsgEvent.DELAY)
                .toStateAndAction(MsgState.WAIT_SEND,null);
        builder
                .state(MsgState.ERROR).entry(stateMachineContext -> {
            System.out.println("报错");
        }).event(MsgEvent.ERROR);
        builder.state(MsgState.END).exit(stateMachineContext -> {
            System.out.println("完成");
        });
        return builder.build();
    }

    public static void main(String[] args) throws IOException {
        StateMachine stateMachine = StateMachineFactory.getStateMachine();
        StateMachineContext context = stateMachine.getContext();
        context.setMsg(new Msg() {
            @Override
            public Long getRecipientId() {
                return null;
            }

            @Override
            public Long getSenderId() {
                return null;
            }

            @Override
            public Long getMsgId() {
                return 1L;
            }
        });
        context.setStateMachine(stateMachine);
        stateMachine.fire(MsgEvent.SEND);
        System.in.read();
    }
}
